package com.fate.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fate.domain.User;
import com.fate.domain.UserAddr;
import com.fate.service.UserAddrService;
import com.sun.org.apache.regexp.internal.RE;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.omg.IOP.ServiceContextHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("p/address")
@Api(tags= "用户收货地址管理")
public class UserAddrController {

    @Autowired
    private UserAddrService userAddrService;

    @GetMapping("list")
    @ApiOperation("全查询收货地址")
    public ResponseEntity<List<UserAddr>> getUserAddr(){
        String userId = SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString();
       List<UserAddr> userAddrs =  userAddrService.getUserAddrList(userId);
        return ResponseEntity.ok(userAddrs);
    }

    @PostMapping("addAddr")
    @ApiOperation("新增用户收货地址")
    public ResponseEntity<Void> addUserAddr(@RequestBody UserAddr userAddr){
        String userId = SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString();
        userAddr.setUserId(userId);
        userAddrService.save(userAddr);
        return ResponseEntity.ok().build();
    }

    @PutMapping("defaultAddr")
    @ApiOperation("修改用户默认收货地址")
    public ResponseEntity<Void> changeUserDefaultAddr(Long addrId){
        String userId = SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString();
        userAddrService.changeUserDefaultAddr(userId,addrId);
        return ResponseEntity.ok().build();
    }

    /**
     * 获取用户的默认收货地址
     */
    @GetMapping("getUserDefaultAddr")
    @ApiOperation("获取用户的默认收货地址")
    UserAddr getUserDefaultAddr(@RequestParam String userId){
        return userAddrService.getOne(new LambdaQueryWrapper<UserAddr>()
            .eq(UserAddr::getUserId,userId)
                .eq(UserAddr::getCommonAddr,1)
        );
    }
}
